package pers.vinsonws.jianghu.serverspring.handers;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pers.vinsonws.jianghu.codeCompont.MsgEveryPro;
import pers.vinsonws.jianghu.serverspring.channel.ChannelManager;
import pers.vinsonws.jianghu.serverspring.session.NetSession;
import pers.vinsonws.jianghu.serverspring.session.SessionManager;
import java.io.IOException;

/**
 * @auther vinsonws
 * @date 2018/11/4 22:15
 */
@Component
@ChannelHandler.Sharable
public class ChatServerHandler extends ChannelInboundHandlerAdapter {
    private static final Logger log = LoggerFactory.getLogger(ChatServerHandler.class);

    @Autowired
    private ServerMainReadProcess serverMainReadProcess;
    @Autowired
    private ChannelManager channelManager;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //当客户端建立连接时：将session加入channel中，session就只有channel、ip其它为空或者false
        if (!SessionManager.addSession(ctx.channel(), new NetSession(ctx.channel()))) {
            ctx.channel().close();
            log.error("repeated session,IP=[{}]",SessionManager.getIp(ctx.channel()));
        } else {
            SessionManager.getSession(ctx.channel()).setIpAddr(SessionManager.getIp(ctx.channel()));
            log.info("IP=[{}]建立连接！",SessionManager.getIp(ctx.channel()));
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("IP=[{}]断开连接连接！",SessionManager.getIp(ctx.channel()));
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("接收到"+ ctx.channel().remoteAddress().toString() +"消息处理中");
        MsgEveryPro.Message message = (MsgEveryPro.Message) msg;
        serverMainReadProcess.readProcess(message, ctx);

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("业务逻辑出错", cause);
        cause.printStackTrace();
        Channel channel = ctx.channel();
        channelManager.removeChannel(SessionManager.getSession(channel).getUser().getId());
        if(cause instanceof IOException && channel.isActive()){
            log.error("simpleclient"+channel.remoteAddress()+"异常");
            //SpringContext.getUserService().userLogout(channel, SessionCloseReason.NORMAL);
            ctx.close();
        }
        ctx.close();
    }
}
